package com.example.demo.common;

import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;
import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 * Description:密码加盐算法
 * User: yyx
 * Date: 2023-11-15
 * Time: 16:57
 */
public class PasswordUtils {

    public static String encrypt(String password){
        //1.得到盐值变成 32位的
        String salt = UUID.randomUUID().toString().replace("-","");
        //2.采用盐值+密码进行MD5加密处理
        String finalPassword = DigestUtils.md5DigestAsHex((salt + password).getBytes(StandardCharsets.UTF_8));
        //3.返回盐值+$+最终密码
        return salt+"$"+finalPassword;
    }

    public static boolean decrypt(String rowPassword,String dbPassword){
        //1.得到盐值
        if(!StringUtils.hasLength(rowPassword)||!StringUtils.hasLength(dbPassword)||
            dbPassword.length()!=65){
            return false;
        }
        String[] strings = dbPassword.split("\\$");
        if(strings.length !=2){
            return false;
        }
        String salt = strings[0];
        String finalPassword = strings[1];
        //2.加密待验证的密码
        String password = DigestUtils.md5DigestAsHex((salt + rowPassword).getBytes(StandardCharsets.UTF_8));
        //3.对比
        if (password.equals(finalPassword)){
            return true;
        }
        return false;
    }
}
